const { app, BrowserWindow, protocol, net, session, globalShortcut, ipcMain, dialog } = require('electron')
const path = require('path')
const nodeUrl = require('url')

console.log('Main process started');

// 存储用户选择的下载目录
let userSelectedDownloadPath = null;

// 注册特权
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { standard: true, secure: true, corsEnabled: true } }
])

function createWindow() {
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      // 推荐关闭 nodeIntegration + 开启 preload
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.cjs')
    },
    icon: path.join(__dirname, '../logo.ico')
  })

  // 添加调试信息，检查webPreferences
  console.log('WebPreferences preload path:', path.join(__dirname, 'preload.cjs'));

  win.webContents.session.on('will-download', (event, item, webContents) => {
    // 使用用户选择的目录或默认下载目录
    const downloadPath = userSelectedDownloadPath || app.getPath('downloads');
    const savePath = path.join(downloadPath, item.getFilename());
    console.log('Save path:', savePath);
    item.setSavePath(savePath);
  });

  // 添加页面加载事件监听
  win.webContents.on('did-finish-load', () => {
    console.log('Page finished loading');
  });

  // 添加控制台消息监听
  win.webContents.on('console-message', (event, level, message, line, sourceId) => {
    console.log('Renderer console message:', level, message, line, sourceId);
  });

  win.setMenu(null)
  
  // 区分开发/生产加载地址
  if (process.env.VITE_DEV_SERVER_URL) {
      console.error('加载页面失败2:')
    win.loadFile(path.join(__dirname, '../dist-prod/index.html'))
    // win.webContents.openDevTools({ mode: 'bottom' });
  } else {
    // 生产环境使用 app 协议直接加载，避免重复初始化
    // win.loadURL('http://localhost:80/').catch((err) => {
      // console.error('加载页面失败:', err)
      // 如果 app 协议加载失败，尝试使用 file 协议
      const indexPath = path.join(__dirname, '../dist-prod/index.html')
      win.loadFile(indexPath);
    // })

    // win.webContents.openDevTools({ mode: 'right' });
  }
  globalShortcut.register('CommandOrControl+Shift+i', function () {
    win.webContents.openDevTools()
  })
  
  return win
}

// 监听渲染进程发送的IPC消息 - 使用 handle 来响应 invoke 调用
ipcMain.handle('open-directory-dialog', async (event) => {
  console.log('Received open-directory-dialog request');
  // 获取当前窗口
  const win = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
  
  if (!win) {
    console.error('No window found for dialog');
    return null;
  }
  
  const { canceled, filePaths } = await dialog.showOpenDialog(win, {
    title: '选择文件夹',
    properties: ['openDirectory', 'createDirectory'], // 允许选择文件夹并创建新文件夹
  });
  console.log('Dialog result:', canceled, filePaths);

  if (!canceled && filePaths.length > 0) {
    // 保存用户选择的目录
    userSelectedDownloadPath = filePaths[0];
    console.log('User selected download path:', userSelectedDownloadPath);
    // 返回选择的文件夹路径
    console.log('Returning selected path:', filePaths[0]);
    return filePaths[0];
  } else {
    // 如果用户取消了操作，返回null
    console.log('No directory selected or operation cancelled');
    return null;
  }
});

// 处理获取路径的请求
ipcMain.handle('get-path', async (event, name) => {
  console.log('Received get-path request for:', name);
  return app.getPath(name);
});

// 处理获取应用程序路径的请求
ipcMain.handle('get-app-path', async (event) => {
  console.log('Received get-app-path request');
  return __dirname;
});

app.whenReady().then(() => {
  console.log('App is ready');
  createWindow()
  
  // 其他在app准备好后需要执行的代码可以放在这里
})
app.on('window-all-closed', () => {
  console.log('All windows closed, quitting app');
  app.quit()
})